<template>
  <h1>签到表管理</h1>
  <el-table :data="signInFormData" style="width: 100%" >
    <el-table-column prop="aname" label="活动名称" />
    <el-table-column prop="atype" label="活动类型" />
    <el-table-column prop="updatetime" label="最后修改时间" />
    <el-table-column label="导出" fixed="right" width="250">
      <template #default="scope">
        <el-button size="small" type="success" @click="generateLink(scope.row)">链接生成</el-button>
        <el-button size="small" type="success" @click="generateQrCode(scope.row)">二维码生成</el-button>
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" width="250">
      <template #default="scope">
        <el-button type="primary"  size="small" @click="showDetails(scope.row.aid)">查看</el-button>
        <el-button type="primary"  size="small" @click="editDetails(scope.row.aid)">修改</el-button>
        <el-popconfirm
          title="确定要删除此签到表吗？"
          @confirm="() => handleDelete(scope.row.aid)"
        >
          <template #reference>
            <el-button size="small" type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>

  <!-- 查看 -->
  <el-dialog v-model="dialogVisible" width="50%">
    <el-form label-width="100px">
      <!-- {{ details }} -->
      <h1>活动名称：{{ details.aname }}</h1>
      <hr>
      <el-form-item label="活动主类型:">{{ details.atype }}</el-form-item>
      <el-form-item label="活动副类型:">{{ details.types }}</el-form-item>
      <el-form-item label="活动时间:">{{ details.atime }}</el-form-item>

      <el-form-item label="学生学号:">
        <el-input v-model="signInData.sid" placeholder="请填写学号"></el-input>
      </el-form-item>
      <el-form-item label="学生姓名:">
        <el-input v-model="signInData.sname" placeholder="请填写姓名"></el-input>
      </el-form-item>
      <el-form-item label="学生班级:">
        <el-input v-model="signInData.sclass" placeholder="请填写班级"></el-input>
      </el-form-item>

      <!-- 动态生成输入框 -->
      <el-form-item v-if="details.message1" :label="details.message1">
        <el-input v-model="signInData.remessage1" :placeholder="details.message1 ? '请填写' + details.message1 : '请填写内容'"></el-input>
      </el-form-item>
      <el-form-item v-if="details.message2" :label="details.message2">
        <el-input v-model="signInData.remessage2" :placeholder="details.message2 ? '请填写' + details.message2 : '请填写内容'"></el-input>
      </el-form-item>
      <el-form-item v-if="details.message3" :label="details.message3">
        <el-input v-model="signInData.remessage3" :placeholder="details.message3 ? '请填写' + details.message3 : '请填写内容'"></el-input>
      </el-form-item>
      <el-form-item v-if="details.message4" :label="details.message4">
        <el-input v-model="signInData.remessage4" :placeholder="details.message4 ? '请填写' + details.message4 : '请填写内容'"></el-input>
      </el-form-item>
      <el-form-item v-if="details.message5" :label="details.message5">
        <el-input v-model="signInData.remessage5" :placeholder="details.message5 ? '请填写' + details.message5 : '请填写内容'"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitSignIn">确认签到</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 修改 -->
  <el-dialog v-model="changeDialogVisible" title="修改签到表" width="50%">
    <el-form label-width="100px">
      <!-- {{ changedetails }} -->
      <el-form-item label="活动名称" prop="aname">
        <el-input v-model="changeData.aname" :placeholder="changedetails.aname"></el-input>
      </el-form-item>
      
      <el-form-item label="活动主类型" prop="atype">
        <el-select v-model="changeData.atype" :placeholder="changedetails.atype" @change="updateSubTypes">
          <el-option label="创造能力" value="创造能力"></el-option>
          <el-option label="文体能力" value="文体能力"></el-option>
          <el-option label="社会实践能力" value="社会实践能力"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="活动副类型" prop="types">
        <el-select v-model="changeData.types" :placeholder="subTypesPlaceholder" :disabled="!subTypes || subTypes.length === 0">
          <el-option v-for="(option, index) in subTypes" :key="index" :label="option" :value="option"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="活动时间" prop="date">
        <el-date-picker
          v-model="changeData.date"
          type="datetime"
          placeholder="选择活动时间"
          clearable="clearable"
          style="width: 100%;"
        ></el-date-picker>
      </el-form-item>
      
      <br><hr><br>

      <el-form-item label="学生学号:">
        <el-input  :disabled="true" placeholder="固定收集项无需填写"></el-input>
      </el-form-item>
      <el-form-item label="学生姓名:">
        <el-input :disabled="true" placeholder="固定收集项无需填写"></el-input>
      </el-form-item>
      <el-form-item label="学生班级:">
        <el-input :disabled="true" placeholder="固定收集项无需填写"></el-input>
      </el-form-item>

      <!-- 动态生成输入框 -->
      <el-form-item v-if="changedetails.message1" label="自定义信息1">
        <el-input v-model="changeData.message1" :placeholder="changedetails.message1"></el-input>
      </el-form-item>
      <el-form-item v-if="changedetails.message2" label="自定义信息2">
        <el-input v-model="changeData.message2" :placeholder="changedetails.message2"></el-input>
      </el-form-item>
      <el-form-item v-if="changedetails.message3" label="自定义信息3">
        <el-input v-model="changeData.message3" :placeholder="changedetails.message3"></el-input>
      </el-form-item>
      <el-form-item v-if="changedetails.message4" label="自定义信息4">
        <el-input v-model="changeData.message4" :placeholder="changedetails.message4"></el-input>
      </el-form-item>
      <el-form-item v-if="changedetails.message5" label="自定义信息5">
        <el-input v-model="changeData.message5" :placeholder="changedetails.message5"></el-input>
      </el-form-item>

      <!-- 动态生成输入框 -->
      <!-- <el-form-item v-for="i in 5" :key="`message-${i}`" v-if="changedetails[`message${i}`]" :label="'自定义信息' + i">
        <el-input v-model="changeData[`message${i}`]" :placeholder="changedetails[`message${i}`]"></el-input>
      </el-form-item> -->

    <!-- 添加新增和删除按钮 -->
    <el-form-item>
      <el-button type="success" @click="addMessage" :disabled="nonEmptyMessageCount >= 5">+</el-button>
    </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitEdit(changedetails.aid)">保存修改</el-button>
      </span>
    </template>
  </el-dialog>
</template>


<script setup>
import { ref, onMounted } from 'vue';
import { useStore } from 'vuex';
import axiosInstance from '@/plugins/Axios.js';
import { ElMessage } from 'element-plus';

const store = useStore();

// 响应式引用
const signInFormData = ref([]);
const signInData = ref({});
const changeData = ref({
  aname: '',
  atype: '',
  types: '',
  date: '',
  sid: '',
  sname: '',
  sclass: '',
  message1: '',
  message2: '',
  message3: '',
  message4: '',
  message5: '',
});
//两次窗口查询返回结果
const details = ref({});
const changedetails = ref({});
//窗口默认状态
const dialogVisible = ref(false);
const changeDialogVisible = ref(false);
// 类型选择器
const subTypes = ref([]);
const subTypesPlaceholder = ref('');
// 自定义信息输入框数量
const nonEmptyMessageCount = ref(0);
// 定义用于存储第一个空 message 键名的索引
const firstEmptyMessageIndex = ref(null);


// 获取签到表数据
const fetchSignForm = async () => {
  try {
    console.log('获取签到表数据');
    const did = store.getters.CurrentUser.did;
    if (!did) {
      console.warn('当前用户未登录或登录信息尚未准备好');
      return;
    }
    const response = await axiosInstance.getDepartmentPbActivities(did);
    signInFormData.value = response.data;
  } catch (error) {
    console.error('获取签到表数据失败时出错:', error);
    ElMessage.error('获取签到表数据失败');
  }
};

// 页面加载时获取所有数据
onMounted(() => {
  fetchSignForm();
});

// 更新副类型的选项列表
const updateSubTypes = () => {
  switch (changeData.value.atype) {
    case '创造能力':
      subTypes.value = ['学科竞赛', '校科研项目', '报刊投稿录用', '其它项'];
      break;
    case '文体能力':
      subTypes.value = ['体育竞赛', '文艺竞赛', '校内外各种艺术比赛', '其它项'];
      break;
    case '社会实践能力':
      subTypes.value = ['公益事业', '参加三下乡', '校系组织的讲座', '网络平台参与比赛', '其他项', '其它项'];
      break;
    default:
      subTypes.value = [];
  }
  subTypesPlaceholder.value = `请选择${changeData.value.atype}相关的副类型`;
  // 更新 message 计数器
  updateNonEmptyMessageCount();
};



// 更新非空 message 项的数量以及找到第一个空的 message 键名
const updateNonEmptyMessageCount = () => {
  nonEmptyMessageCount.value = 0;
  firstEmptyMessageIndex.value = null;
  for (let i = 1; i <= 5; i++) {
    const key = `message${i}`;
    if (changeData.value[key]) {
      nonEmptyMessageCount.value++;
    }else { 
      // 找到第一个空的 message 键名的索引
      firstEmptyMessageIndex.value = i;
      break;
    }
  }
};

// 添加新的 message 表单项
const addMessage = () => {
  if (firstEmptyMessageIndex.value !== null) {
    // 获取下一个可用的 message 键名
    const key = `message${firstEmptyMessageIndex.value}`;
    // 初始化这个新的 message 键
    changeData.value[key] = ''; // 或者设置一个默认值
  }
};




// 删除签到表
const handleDelete = async (aid) => {
  try {
    await axiosInstance.deleteActivity(aid);
    ElMessage.success('活动删除成功');
    fetchSignForm(); // 刷新列表
  } catch (error) {
    console.error('删除活动失败:', error);
    ElMessage.error('删除活动失败');
  }
};

/* showdetails和editdetails这里代码看似冗余了。但如果不分别进行两次查找，都用同一个查找的数据的话，这样会导致比方说：
 查看一个签到表详情，去修改其他的签到表的时候，无论选择哪一个签到表，点击修改打开的全部都会是查找时的那个签到表的设计数据
 看到这里可能会问，那为什么不用同一个弹窗，因为是不同操作，查看数据窗口有签到功能、字段固定的只需要输入，
 但修改数据可以修改签到表信息、功能操作不同要用到的窗口也是不同的，所以还是得分开设计*/

// 查看按钮——查看详情
const showDetails = async (aid) => {
  try {
    console.log('查看详情的签到表id', aid);
    const response = await axiosInstance.selectPbActivity(aid);
    details.value = response.data; // 将响应数据赋值给 details
    dialogVisible.value = true; // 显示模态框
  } catch (error) {
    console.error('获取签到表详情失败:', error);
    ElMessage.error('获取签到表详情失败');
  }
};

// 修改按钮——查看详情
const editDetails =async (aid) => {
  try {
    const did = store.getters.CurrentUser.did;
    console.log('修改活动的部门id:', did);
    console.log('修改-查看详情的签到表id', aid);
    const response = await axiosInstance.selectPbActivity(aid);
    changedetails.value = response.data; // 将响应数据赋值给 details
    updateSubTypes(); // 初始化副类型
    changeDialogVisible.value = true;
  } catch (error) {
    console.error('获取签到表详情失败:', error);
    ElMessage.error('获取签到表详情失败');
  }
};

// 确认签到操作
const submitSignIn = async () => {
  try {
    const activityData = {
      aid: details.value.aid,
      aname: details.value.aname,
      did: details.value.did,
      sid: signInData.value.sid,
      sname: signInData.value.sname,
      sclass: signInData.value.sclass,
      atype: details.value.atype,
      types: details.value.types,
      remessage1: signInData.value.remessage1,
      remessage2: signInData.value.remessage2,
      remessage3: signInData.value.remessage3,
      remessage4: signInData.value.remessage4,
      remessage5: signInData.value.remessage5,
    };
    await axiosInstance.addSignInData(activityData);
    signInData.value = {}; // 清空表单数据
    dialogVisible.value = false; // 关闭对话框

  } catch (error) {
    console.error('签到失败:', error);
    ElMessage.error('签到失败');
  }
};

// 保存修改
const submitEdit = async (aid) => {
  try {
    const did = store.getters.CurrentUser.did;
    // 构造要更新的数据
    const pbActivityData = {
      aid: aid,
      did: did,
      aname: changeData.value.aname,
      atype: changeData.value.atype,
      types: changeData.value.types,
      atime: changeData.value.atime,
      message1: changeData.value.message1 || '',
      message2: changeData.value.message2 || '',
      message3: changeData.value.message3 || '',
      message4: changeData.value.message4 || '',
      message5: changeData.value.message5 || '',
    };
    console.log('修改活动数据:', pbActivityData);
    await axiosInstance.updatePbActivity(pbActivityData);
    changeData.value = {}; // 清空表单数据
    ElMessage.success('活动修改成功');
    changeDialogVisible.value = false;
    // 刷新列表
    fetchSignForm();
  } catch (error) {
    console.error('修改活动失败:', error);
    ElMessage.error('修改活动失败');
  }
};

// 生成链接
const generateLink = (row) => { 
  console.log('生成链接:', row);
};

// 生成二维码 
const generateQrCode = (row) => { 
  console.log('生成二维码:', row);
};
</script>